"""Discriminating wrapper for grep.

We ignore the following:
- Files/directories that start with a dot
- Files that end with ~
- Files of the type py[co]
"""
import subprocess
import os.path
import optparse
import sys

import aktoolbox


def _error(message):
    sys.stderr.write("%s\n" % message)
    sys.exit(1)


def _debug(message):
    if _opts.verbose:
        sys.stderr.write("%s\n" % message)


def _grep(fpaths):
    if isinstance(fpaths, basestring):
        fpaths = [fpaths]
    cmd = ["grep"] + _cl_opts + [_pattern] + fpaths
    _debug("Running: %s" % cmd)
    subprocess.call(cmd)

def _grep_recursive(pathname):
    for dpath, dnames, fnames in os.walk(pathname):
        for dname in dnames[:]:
            if dname.startswith("."):
                _debug("Ignoring directory '%s'" % os.path.join(dpath, dname))
                dnames.remove(dname)

        for fname in fnames[:]:
            ext = os.path.splitext(fname)[1][1:]
            if (fname.startswith(".") or fname.endswith("~") or ext in ("pyc",
                "pyo")):
                _debug("Ignoring file '%s'" % os.path.join(dpath, fname))
                continue

            _grep(os.path.join(dpath, fname))

def main():
    """Entry-point for akgrep script."""
    global _opts, _pattern, _cl_opts

    clparser = optparse.OptionParser(usage="%prog [options] pattern path")
    clparser.add_option("-v", "--verbose", action="store_true", help=
            "Enable verbosity", default=False)
    clparser.add_option("-i", "--ignore-case", action="store_true",
            default=False, help="Ignore case distinctions")
    clparser.add_option("-r", "--recursive", action="store_true", help=
            "Enable recursion", default=False)
    clparser.add_option("-H", "--with-filename", action="store_true", default=
            False, help="Print the filename for each match")
    clparser.add_option("--version", action="store_true", help=
            "Print the version number and exit", default=False)
    _opts, args = clparser.parse_args()

    if _opts.version:
        print "AKGrep %s" % (aktoolbox.__version__,)
        sys.exit(0)

    try:
        _pattern, pathnames = args[0], args[1:]
    except ValueError:
        clparser.error("Wrong number of arguments")

    _cl_opts = []
    if _opts.ignore_case:
        _cl_opts.append("-i")
    if not _opts.recursive:
        # Enforce that we can't grep directories
        for pathname in pathnames:
            if os.path.isdir(pathname):
                _error("'%s' is a directory" % (pathname,))
    else:
        # grep implicitly turns on this option in recursive mode
        _cl_opts.append("-H")

    for pathname in pathnames:
        if not os.path.isdir(pathname):
            _grep(pathname)
        else:
            _grep_recursive(pathname)


if __name__ == "__main__":
    main()
